﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Drawing.Design;
using System.ComponentModel;
using System.Windows.Forms.Design;
using System.Windows.Forms;

namespace SampleControls {
    internal class ContentSerializationWithSmartTagEditor : UITypeEditor {

        /// <summary>
        /// Displays an ellipsis (...) button to start a modal dialog box.
        /// </summary>
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) {
            return UITypeEditorEditStyle.Modal;
        }

        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) {
            if (provider != null) {
                IWindowsFormsEditorService editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
                if (editorService != null) {
                    ContentSerializationWithSmartTag controlValue = null;

                    //se for pela smart-tag
                    if (context.Instance.GetType() == typeof(ContentSerializationWithSmartTagActionList)) {
                        var actionList = (ContentSerializationWithSmartTagActionList)context.Instance;
                        var flags = BindingFlags.Instance | BindingFlags.NonPublic;
                        var control = actionList.GetType().GetField("LinkedControl", flags);
                        controlValue = (ContentSerializationWithSmartTag)control.GetValue(actionList);
                    } else if (context.Instance.GetType() == typeof(ContentSerializationWithSmartTag)) {
                        controlValue = (ContentSerializationWithSmartTag)context.Instance;
                    }

                    var selectionControl = new FormContentSerializationWithSmartTag(controlValue);

                    if (editorService.ShowDialog(selectionControl) == DialogResult.OK) {
                        value = selectionControl.Value;
                    }
                }
            }
            return value;
        }

        /// <summary>
        /// No special thumbnail will be shown for the grid.
        /// </summary>
        public override bool GetPaintValueSupported(System.ComponentModel.ITypeDescriptorContext context) {
            return false;
        }
    }
}
